package cn.jiedh.app.meiweidk.forgetpsw;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.MyTBView;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.BitmapUtil;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.StringUtil;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.Utils.tool.ValidateUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.buried.BuriedBean;
import cn.jiedh.app.meiweidk.entity.ForgetPswBean;
import cn.jiedh.app.meiweidk.entity.ImageCodeBean;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;


/**
 * @name：忘记密码
 * @author： 司马林
 * @phone： 18423134135
 * @createTime： 2017/10/19
 * @modifyTime： 2017/10/19
 */
public class ForgetPswActivity extends BaseActivity {
    @BindView(R.id.bar_tv_title)
    TextView title;
    @BindView(R.id.phone)
    EditText phoneEdt;
    @BindView(R.id.verification_edt)
    EditText verificationEdt;
    @BindView(R.id.verification_btn)
    MyTBView verificationBtn;
    @BindView(R.id.coordinator)
    CoordinatorLayout coordinatorLayout;
    @BindView(R.id.forget_psw_next_btn)
    Button forgetPswNextBtn;
    @BindView(R.id.image_code_edt)
    EditText imageCodeEdt;
    @BindView(R.id.image_code_img)
    ImageView imageCodeImg;
    @BindView(R.id.image_code_layout)
    LinearLayout imageCodeLayout;

    private String img = "";
    private String imgKey = "";
    private String phone;

    private List<BuriedBean> buriedList;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_forget_psw;
    }

    @Override
    protected void initView(View view) {
        title.setText("找回登录密码");
        if (SPUtils.getIsLogin()) {
            phone = SPUtils.getPhone();
            String maskNumber = phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
            phoneEdt.setText(maskNumber);
            phoneEdt.setFocusable(false);
            phoneEdt.setFocusableInTouchMode(false);

        } else {
            phoneEdt.setHint("请输入手机号");
            phoneEdt.setFocusableInTouchMode(true);
            phoneEdt.setFocusable(true);
            phoneEdt.requestFocus();
        }
        verificationEdt.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

                goResetPsw();
                return true;
            }
            return false;
        });
    }

    @OnClick({R.id.bar_img_back, R.id.forget_psw_next_btn, R.id.verification_btn, R.id.image_code_img})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bar_img_back:
                ActivityUtil.goBack(this);
                break;
            case R.id.forget_psw_next_btn:
                goResetPsw();
                break;
            case R.id.verification_btn:

                InputMethodManager imm = (InputMethodManager) verificationBtn.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(verificationBtn.getWindowToken(), 0);
                MobclickAgent.onEvent(activity,"my_setting_findpwd_getverify");
                SPUtils.saveBuried("click","0","找回密码-获取验证码","true","找回密码",
                        "","","");
                if (!SPUtils.getIsLogin()) {
                    phone = phoneEdt.getText().toString();
                }
//                if (StringUtil.isMobileNO(phone)) {
                    getSMSVerificationCode(phone);
//                } else {
//                    T.showShortCenterToast("请输入正确的手机号");
//                }
                break;
            case R.id.image_code_img:
                getImageCode();
                break;
            default:
                break;
        }
    }

    @Override
    protected void initData() {
        getImageCode();
    }

    private void getSMSVerificationCode(String phone) {
        verificationBtn.start();
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("imgKey", imgKey);
        map.put("imgCode", imageCodeEdt.getText().toString());
        request(this, UrlUtils.FORGETSMSCODE, map, false, response -> {
            dismissLoadingDialog();
            if (0 != response.getCode()) {
                T.showShort(response.getMessage());
            }
        });
    }

    private void goResetPsw() {
        InputMethodManager imm = (InputMethodManager) forgetPswNextBtn.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(forgetPswNextBtn.getWindowToken(), 0);

        if (!SPUtils.getIsLogin()) {
            phone = phoneEdt.getText().toString();
        }
        String verification = verificationEdt.getText().toString();
        String errorStr = ValidateUtils.verificationLogin(phone, verification);
        if ("".equals(errorStr)) {
            MobclickAgent.onEvent(activity,"my_setting_findpwd_nextstep");
            SPUtils.saveBuried("click","0","找回密码-下一步点击","",
                    "找回密码","","","");
            Map<String, Object> map = new HashMap<>();
            map.put("phone", phone);
            map.put("code", verificationEdt.getText().toString());
            showLoadingDialog();
            request(this, UrlUtils.FORGETPSW, map, true, new ResponseSuccess<ForgetPswBean>() {
                @Override
                public void onRequestSucceed(BaseResponse<ForgetPswBean> response) {
                    dismissLoadingDialog();
                    if (0 == response.getCode()) {
                        Bundle bundle = new Bundle();
                        bundle.putString("forgetKey", response.getData().getForgetKey());
                        ActivityUtil.next(ForgetPswActivity.this, ResetPswActivity.class, bundle);
                    } else {
                        T.showShort(response.getMessage());
                    }
                }
            });
        } else {
            T.showShortCenterToast(errorStr);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }


    private void getImageCode() {
        Map<String, Object> map = new HashMap<>();
        showLoadingDialog();
        request(this, UrlUtils.IMAGECODE, map, false, new ResponseSuccess<ImageCodeBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<ImageCodeBean> response) {
                dismissLoadingDialog();
                if (0 == response.getCode()) {
                    imageCodeLayout.setVisibility(View.GONE);
                } else if (1 == response.getCode()) {
                    T.showShort(response.getMessage());

                    imageCodeLayout.setVisibility(View.GONE);
                } else if (3 == response.getCode()) {
                    img = response.getData().getImg();
                    imgKey = response.getData().getImgKey();

                    Bitmap b = BitmapUtil.stringtoBitmap(img);
                    imgKey = response.getData().getImgKey();
                    imageCodeImg.setImageBitmap(b);
                    imageCodeLayout.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        verificationBtn.stop();
        MobclickAgent.onPause(this);
    }
}
